Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports DotNetNuke
Imports DotNetNuke.Services.Localization.Localization
Imports Bring2mind.DNN.Modules.UserFiles.Business

Namespace Bring2mind.DNN.Modules.UserFiles.Controls

 Public Class UserFiles
  Inherits ModuleBase
  Implements DotNetNuke.Entities.Modules.IActionable

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub
  Protected WithEvents dgFiles As System.Web.UI.WebControls.DataGrid
  Protected WithEvents NewFile As System.Web.UI.HtmlControls.HtmlInputFile
  Protected WithEvents cmdUpload As System.Web.UI.WebControls.LinkButton
  Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
  Protected WithEvents pnlUpload As System.Web.UI.WebControls.Panel
  Protected WithEvents txtMaxSize As System.Web.UI.WebControls.TextBox
  Protected WithEvents Comparevalidator2 As System.Web.UI.WebControls.CompareValidator

  'NOTE: The following placeholder declaration is required by the Web Form Designer.
  'Do not delete or move it.
  Private designerPlaceholderDeclaration As System.Object

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
   'CODEGEN: This method call is required by the Web Form Designer
   'Do not modify it using the code editor.
   InitializeComponent()
  End Sub

#End Region

  Dim SpaceLeft As Integer
  Public OurURL As String
  Public MyDirectory As String
  Private MyUploadDirectory As String

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

   If Not context.User.Identity.IsAuthenticated Then
    dgFiles.Visible = False
    lblMessage.Text = GetString("NeedLogin", Me.LocalResourceFile)
    pnlUpload.Visible = False
    Exit Sub
   End If

   OurURL = DotNetNuke.Common.NavigateURL.Replace("~/", "")
   'MyDirectory = "http://" & PortalAlias.HTTPAlias & "/Portals/" & PortalId & "/UserFiles/User" & UserId & "/"
   MyDirectory = Me.PortalSettings.HomeDirectory & "UserFiles/User" & UserId & "/"
   MyUploadDirectory = Me.UserFilesSettings.UploadDirectory & "User" & UserId & "\"
   If Not IO.Directory.Exists(MyUploadDirectory) Then
    IO.Directory.CreateDirectory(MyUploadDirectory)
   End If

   SpaceLeft = Me.UserFilesSettings.UserQuota - Bring2mind.DNN.Modules.UserFiles.Data.DataProvider.Instance().GetMyTotal(UserInfo.UserID, PortalId)
   lblMessage.Text = String.Format(GetString("SpaceLeft", Me.LocalResourceFile), FormatSize(SpaceLeft), Me.UserFilesSettings.MaxImageSize, Me.UserFilesSettings.ValidExtensions)
   lblMessage.CssClass = "Normal"

   Dim objFiles As New FilesController

   If Not Me.IsPostBack Then
    DotNetNuke.Services.Localization.Localization.LocalizeDataGrid(dgFiles, Me.LocalResourceFile)
    txtMaxSize.Text = Me.UserFilesSettings.MaxImageSize
    dgFiles.PageSize = Me.UserFilesSettings.GridSize
    BindGrid()
   End If
  End Sub

  Private Sub BindGrid()
   Dim dv As DataView = New DataView(DotNetNuke.Common.Globals.ConvertDataReaderToDataTable(Bring2mind.DNN.Modules.UserFiles.Data.DataProvider.Instance().GetMyFiles(UserId, PortalId)))
   dv.Sort = "FileName"
   dgFiles.DataSource = dv
   If dv.Count > 0 Then
    If dgFiles.CurrentPageIndex > (dv.Count - 1) / Me.UserFilesSettings.GridSize Then
     dgFiles.CurrentPageIndex = Int((dv.Count - 1) / Me.UserFilesSettings.GridSize)
    End If
    dgFiles.Visible = True
   Else
    dgFiles.Visible = False
   End If
   dgFiles.DataBind()
  End Sub

  Private Sub dgFiles_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgFiles.PageIndexChanged
   dgFiles.CurrentPageIndex = e.NewPageIndex
   BindGrid()
  End Sub

  Public Function FormatSize(ByVal Bts As Integer) As String
   If Bts > 1024 ^ 3 Then
    Return (Bts / 1024 ^ 3).ToString("0.0") & " GB"
   ElseIf Bts > 1024 ^ 2 Then
    Return (Bts / 1024 ^ 2).ToString("0.0") & " MB"
   ElseIf Bts > 1024 Then
    Return (Bts / 1024).ToString("0.0") & " KB"
   Else
    Return Bts.ToString("0,000") & " B"
   End If
  End Function

  Private Sub cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpload.Click

   Dim ErrorMsg As String = ""
   Dim FileLength As Integer

   'check that we have a file and that it's not too big
   If NewFile.PostedFile Is Nothing Then Exit Sub
   FileLength = NewFile.PostedFile.ContentLength
   Select Case FileLength
    Case Is < 1
     ErrorMsg = GetString("NoFile", Me.LocalResourceFile)
    Case Is > Me.UserFilesSettings.MaxFileLength
     ErrorMsg = GetString("FileTooBig", Me.LocalResourceFile)
    Case Is > SpaceLeft
     ErrorMsg = GetString("Quota Exceeded", Me.LocalResourceFile)
   End Select
   Dim Ext As String = System.Text.RegularExpressions.Regex.Replace(NewFile.PostedFile.FileName, ".*\.", "")
   If InStr(Me.UserFilesSettings.ValidExtensions, "." & Ext & ";") = 0 Then
    ErrorMsg = "File type not permitted"
   End If
   If ErrorMsg <> "" Then
    lblMessage.CssClass = "NormalRed"
    lblMessage.Text = ErrorMsg
    Exit Sub
   End If

   'now save it to disk
   Dim NewFileName As String = System.Text.RegularExpressions.Regex.Replace(NewFile.PostedFile.FileName, ".*\\", "").Replace(" ", "_")
   Dim bOverwrite As Boolean = IO.File.Exists(MyUploadDirectory & NewFileName)
   NewFile.PostedFile.SaveAs(MyUploadDirectory & NewFileName)

   'If it's an image then check the image size and resize if needed
   If InStr(NewFile.PostedFile.ContentType, "image") > 0 Then
    If Integer.Parse(txtMaxSize.Text) < Me.UserFilesSettings.MaxImageSize Then
     Globals.ResizeImage(MyUploadDirectory & NewFileName, Integer.Parse(txtMaxSize.Text))
    Else
     Globals.ResizeImage(MyUploadDirectory & NewFileName, Me.UserFilesSettings.MaxImageSize)
    End If
    Dim fi As New IO.FileInfo(MyUploadDirectory & NewFileName)
    FileLength = fi.Length
   End If

   'now add it to the database
   Dim Fls As New FilesController
   If bOverwrite Then
    Dim Fl As FilesInfo = Fls.GetFileByFilename(NewFileName, UserId, PortalId)
    With fl
     .DateSubmitted = Now
     .FileLength = FileLength
    End With
    Fls.UpdateFiles(fl)
   Else
    Dim Fl As New FilesInfo
    With Fl
     .DateSubmitted = Now
     .FileLength = FileLength
     .FileName = NewFileName
     .PortalId = PortalId
     .UserId = UserId
    End With
    Fls.AddFiles(Fl)
   End If

   BindGrid()
   SpaceLeft = Me.UserFilesSettings.UserQuota - Bring2mind.DNN.Modules.UserFiles.Data.DataProvider.Instance().GetMyTotal(UserId, PortalId)
   lblMessage.Text = String.Format(GetString("SpaceLeft", Me.LocalResourceFile), FormatSize(SpaceLeft), Me.UserFilesSettings.MaxImageSize, Me.UserFilesSettings.ValidExtensions)

  End Sub

  Private Sub dgFiles_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgFiles.DeleteCommand
   Try
    Dim objFiles As New FilesController
    Dim objFile As FilesInfo = objFiles.GetFiles(dgFiles.DataKeys(e.Item.ItemIndex), PortalId)
    If Not objFile Is Nothing Then
     IO.File.Delete(MyUploadDirectory & objFile.FileName)
     objFiles.DeleteFiles(objFile.id)
    End If

    BindGrid()
    SpaceLeft = Me.UserFilesSettings.UserQuota - Bring2mind.DNN.Modules.UserFiles.Data.DataProvider.Instance().GetMyTotal(UserInfo.UserID, PortalId)
    lblMessage.Text = String.Format(GetString("SpaceLeft", Me.LocalResourceFile), FormatSize(SpaceLeft), Me.UserFilesSettings.MaxImageSize, Me.UserFilesSettings.ValidExtensions)

   Catch exc As Exception 'Module failed to load
    DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, exc)
   End Try

  End Sub

  Private Sub dgFiles_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgFiles.ItemCreated
   Try
    Dim cmdDelete As Control = e.Item.FindControl("cmdDelete")

    If Not cmdDelete Is Nothing Then
     CType(cmdDelete, ImageButton).Attributes.Add("onClick", "javascript: return confirm('" & GetString("ConfirmDelete", Me.LocalResourceFile) & "')")
    End If

   Catch exc As Exception 'Module failed to load
    DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, exc)
   End Try
  End Sub

  Public ReadOnly Property ModuleActions() As DotNetNuke.Entities.Modules.Actions.ModuleActionCollection Implements DotNetNuke.Entities.Modules.IActionable.ModuleActions
   Get
    Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
    Actions.Add(GetNextActionID, "All Files List", Entities.Modules.Actions.ModuleActionType.ContentOptions, "", "", EditUrl("AllFiles"), False, DotNetNuke.Security.SecurityAccessLevel.Admin, True, False)
    Return Actions
   End Get
  End Property
 End Class

End Namespace
